<template>
  <div class="employee-manage-page">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button @click="handleBatch">批量操作</el-button>
      <el-button @click="handleImport">导入</el-button>
      <el-button @click="handleExport">导出</el-button>
      <el-select v-model="queryParams.roleId" placeholder="所属角色" style="width: 150px; margin-left: 20px;">
        <el-option label="全部" value=""></el-option>
        <el-option v-for="role in roleOptions" :key="role.roleId" :label="role.roleName" :value="role.roleId"></el-option>
      </el-select>
      <el-input
        v-model="queryParams.employeeName"
        placeholder="请输入员工姓名搜索"
        style="width: 200px; margin-left: 10px;"
        @keyup.enter.native="handleQuery"
      />
      <el-button type="primary" @click="handleQuery" style="margin-left: 10px;">搜索</el-button>
      <el-button @click="handleReset" style="margin-left: 10px;">重置</el-button>
    </div>

    <!-- 员工表格 -->
    <el-table
      :data="employeeList"
      border
      stripe
      @selection-change="handleSelectionChange"
      style="width: 100%;"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="employeeId" label="员工ID" width="100"></el-table-column>
      <el-table-column prop="employeeAccount" label="员工账号" width="150"></el-table-column>
      <el-table-column prop="employeeName" label="姓名" width="100"></el-table-column>
      <el-table-column prop="deptName" label="所属部门" width="220"></el-table-column>
      <el-table-column prop="roleName" label="所属角色" width="120"></el-table-column>
      <el-table-column label="员工状态" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.employeeStatus === '启用' ? 'success' : 'danger'">
            {{ scope.row.employeeStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="creator" label="创建人" width="100"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160">
        <template #default="scope">
          {{ scope.row.createTime | formatTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row.employeeId)" style="color: #F56C6C;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; text-align: right;"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="isEdit ? '编辑员工' : '新增员工'"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="120px">
        <el-form-item label="员工ID" prop="employeeId" v-if="isEdit">
          <el-input v-model="form.employeeId" placeholder="系统生成" readonly />
        </el-form-item>
        <el-form-item label="员工账号" prop="employeeAccount">
          <el-input v-model="form.employeeAccount" placeholder="请输入员工账号" />
        </el-form-item>
        <el-form-item label="员工姓名" prop="employeeName">
          <el-input v-model="form.employeeName" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <treeselect
            v-model="form.deptId"
            :options="deptOptions"
            :normalizer="normalizer"
            placeholder="请选择所属部门"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="所属角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择所属角色">
            <el-option v-for="role in roleOptions" :key="role.roleId" :label="role.roleName" :value="role.roleId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工状态" prop="employeeStatus">
          <el-select v-model="form.employeeStatus" placeholder="请选择状态">
            <el-option label="启用" value="启用"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 上传excel弹窗 -->
    <el-dialog
      title="导入员工数据"
      :visible.sync="importDialogVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="upload-area" :class="{ 'dragover': isDragging }"
           @drop="handleDrop"
           @dragover.prevent="isDragging = true"
           @dragleave.prevent="isDragging = false"
           @click="$refs.uploadInput.click()">
        <input type="file" ref="uploadInput" accept=".xlsx, .xls" style="display: none" @change="handleFileSelect">
        <i class="el-icon-upload el-icon--large" style="font-size: 48px; color: #409EFF;"></i>
        <p>将文件拖到此处，或<em>点击上传</em></p>
        <p class="upload-tip">支持 .xlsx 或 .xls 格式文件</p>
      </div>
      <template v-if="importFile" class="file-info">
        <div class="file-name">{{ importFile.name }}</div>
        <el-progress :percentage="uploadProgress" v-if="uploadProgress > 0 && uploadProgress < 100"></el-progress>
      </template>
      <!-- Excel模板格式说明 -->
      <div class="format-tips" v-if="!importFile">
        <p class="format-title">Excel文件格式要求：</p>
        <p class="format-item">1. 第1列：员工账号（文本类型）</p>
        <p class="format-item">2. 第2列：员工姓名（文本类型）</p>
        <p class="format-item">3. 第3列：部门ID（数字类型）</p>
        <p class="format-item">4. 第4列：角色ID（数字类型）</p>
        <p class="format-item">5. 第5列：员工状态（文本类型，可选：启用/禁用）</p>
        <p class="format-warning">请确保Excel文件包含正确的列顺序和数据类型！</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelImport">取消</el-button>
          <el-button type="primary" @click="handleImportConfirm" :loading="importLoading">导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listEmployee, getEmployee, addEmployee, updateEmployee, deleteEmployee, exportEmployee, importEmployee } from "@/api/tms/set/employee";
import { getRoleList } from "@/api/tms/set/role";
import { treeSelect } from "@/api/tms/set/department";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as XLSX from "xlsx";

export default {
  name: "Employee",
  components: {
    Treeselect
  },
  filters: {
    formatTime(time) {
      return time ? new Date(time).toLocaleString() : "-";
    }
  },
  data() {
    return {
      employeeList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        employeeName: "",
        roleId: ""
      },
      dialogVisible: false,
      form: {
        employeeId: '',         // 员工ID
        employeeAccount: '',    // 员工账号
        employeeName: '',       // 员工姓名
        deptId: null,      // 所属部门ID
        roleId: '',             // 所属角色ID
        employeeStatus: '启用'  // 员工状态，默认为启用
      },                        // 弹窗表单数据，预先定义所有字段
      formRules: {
        employeeAccount: [{ required: true, message: "请输入员工账号", trigger: "blur" }],
        employeeName: [{ required: true, message: "请输入员工姓名", trigger: "blur" }],
        deptId: [{ required: true, message: "请选择所属部门", trigger: "change" }],
        roleId: [{ required: true, message: "请选择所属角色", trigger: "change" }],
        employeeStatus: [{ required: true, message: "请选择员工状态", trigger: "change" }]
      },
      isEdit: false,
      deptOptions: [],
      roleOptions: [],
      selectedRows: [],
      // 导入相关数据
      importDialogVisible: false,
      importFile: null,
      isDragging: false,
      uploadProgress: 0,
      importLoading: false
    };
  },
  created() {
    this.getList();
    this.getRoleOptions();
    this.getDeptOptions();
  },
  methods: {
    normalizer(node) {
      return {
        id: node.id,
        label: node.label,
        children: node.children || []
      };
    },
    getList() {
      listEmployee(this.queryParams).then(response => {
        this.employeeList = response.rows;
        this.total = response.total;
      });
    },
    getRoleOptions() {
      getRoleList({ pageNum: 1, pageSize: 100 }).then(response => {
        this.roleOptions = response;
      });
    },
    getDeptOptions() {
      treeSelect().then(response => {
        this.deptOptions = response.data || [];
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleReset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        employeeName: "",
        roleId: ""
      };
      this.getList();
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    handleAdd() {
      this.isEdit = false;
      // 重置form对象的所有字段，而不是覆盖整个对象
      this.form.employeeId = '';
      this.form.employeeAccount = '';
      this.form.employeeName = '';
      this.form.deptId = undefined;
      this.form.roleId = '';
      this.form.employeeStatus = '启用';
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.resetFields();
      });
    },
    handleEdit(row) {
      this.isEdit = true;
      getEmployee(row.employeeId).then(response => {
        // 逐个更新字段，而不是覆盖整个form对象
        const employeeData = response.data || {};
        this.form.employeeId = employeeData.employeeId || '';
        this.form.employeeAccount = employeeData.employeeAccount || '';
        this.form.employeeName = employeeData.employeeName || '';
        this.form.deptId = employeeData.deptId;
        this.form.roleId = employeeData.roleId || '';
        this.form.employeeStatus = employeeData.employeeStatus || '启用';
        this.dialogVisible = true;
      });
    },
    handleDelete(employeeId) {
      this.$confirm(`确定删除员工【${employeeId}】吗？`, "提示", {
        type: "warning"
      }).then(() => {
        deleteEmployee(employeeId).then(() => {
          this.$message.success("删除成功");
          this.getList();
        });
      }).catch(() => {});
    },
    handleBatch() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$message.info(`批量操作选中了 ${this.selectedRows.length} 条数据`);
    },
    handleImport() {
      this.importDialogVisible = true;
    },

    // 处理文件选择
    handleFileSelect(e) {
      const file = e.target.files[0];
      if (file) {
        this.validateFile(file);
      }
      // 清空input的值，以便下次选择相同文件也能触发change事件
      e.target.value = '';
    },

    // 处理拖放
    handleDrop(e) {
      e.preventDefault();
      this.isDragging = false;
      const file = e.dataTransfer.files[0];
      if (file) {
        this.validateFile(file);
      }
    },

    // 验证文件格式和大小
    validateFile(file) {
      const fileType = file.name.split('.').pop().toLowerCase();
      const validTypes = ['xlsx', 'xls'];

      if (!validTypes.includes(fileType)) {
        this.$message.error('请上传 .xlsx 或 .xls 格式的文件');
        return;
      }

      const maxSize = 5 * 1024 * 1024; // 5MB
      if (file.size > maxSize) {
        this.$message.error('文件大小不能超过5MB');
        return;
      }

      this.importFile = file;
      this.uploadProgress = 0;
    },

    // 取消导入
    handleCancelImport() {
      this.importDialogVisible = false;
      this.importFile = null;
      this.uploadProgress = 0;
      this.importLoading = false;
    },

    // 确认导入
    handleImportConfirm() {
      if (!this.importFile) {
        this.$message.warning('请选择要导入的Excel文件');
        return;
      }

      this.importLoading = true;

      try {
        // 显示导入确认对话框
        this.$confirm(`确定要导入此Excel文件吗？请确保文件格式符合要求。`, '导入确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 模拟导入进度
          this.uploadProgress = 30;

          // 创建一个新的formData，只包含文件
          const formData = new FormData();
          formData.append('file', this.importFile);

          // 直接调用后端导入API，不进行前端Excel解析
          importEmployee(formData).then(() => {
            this.uploadProgress = 100;
            this.$message.success('导入成功');
            this.getList(); // 刷新列表
            this.handleCancelImport();
          }).catch(() => {
            this.$message.error('导入失败，请重试');
            this.importLoading = false;
          });
        }).catch(() => {
          this.importLoading = false;
        });
      } catch (error) {
        console.error('导入过程中发生错误:', error);
        this.$message.error('导入过程中发生错误');
        this.importLoading = false;
      }
    },

    // 导出员工列表
    handleExport() {
      // 使用前端数据导出，不依赖后端接口
      this.$confirm('确定要导出员工数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        try {
          // 准备导出的数据，只包含需要的字段
          const exportData = this.employeeList.map(row => ({
            '员工ID': row.employeeId,
            '员工账号': row.employeeAccount,
            '员工姓名': row.employeeName,
            '所属部门': row.deptName,
            '所属角色': row.roleName,
            '员工状态': row.employeeStatus,
            '创建时间': row.createTime
          }));

          // 创建工作簿和工作表
          const wb = XLSX.utils.book_new();
          const ws = XLSX.utils.json_to_sheet(exportData);

          // 添加工作表到工作簿
          XLSX.utils.book_append_sheet(wb, ws, '员工列表');

          // 导出Excel文件
          XLSX.writeFile(wb, '员工列表.xlsx');

          this.$message.success('导出成功');
        } catch (error) {
          console.error('导出失败:', error);
          this.$message.error('导出失败，请重试');
        }
      }).catch(() => {});
    },
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const saveFn = this.isEdit ? updateEmployee : addEmployee;
          saveFn(this.form).then(() => {
            this.$message.success(this.isEdit ? "编辑成功" : "新增成功");
            this.dialogVisible = false;
            this.getList();
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.employee-manage-page {
  padding: 16px;
  background-color: #fff;
}
.operation-bar {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}
.upload-area {
  border: 2px dashed #c0c4cc;
  border-radius: 4px;
  padding: 30px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 15px;
}
.upload-area:hover {
  border-color: #409EFF;
}
.upload-area.dragover {
  border-color: #409EFF;
  background-color: #ecf5ff;
}
.upload-area em {
  color: #409EFF;
  cursor: pointer;
}
.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}
.file-info {
  .format-tips {
    margin-top: 15px;
    padding: 10px 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    font-size: 12px;
  }
  .format-title {
    font-weight: bold;
    color: #303133;
    margin-bottom: 8px;
  }
  .format-item {
    color: #606266;
    margin: 4px 0;
    line-height: 1.6;
  }
  .format-warning {
    color: #E6A23C;
    margin-top: 8px;
    font-size: 11px;
    line-height: 1.5;
  }
}
.file-name {
  color: #606266;
  margin-bottom: 10px;
}
</style>
